﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DiscountsDAL;
using System.Collections;

namespace DiscountsBLL
{
    public class ActionEO
    {
        public System.Guid GuidId { get; set; }
        public System.String Name { get; set; }
        public System.String Discription { get; set; }
        public System.Boolean IsDelete { get; set; }
        public System.Boolean IsActive { get; set; }
        public System.DateTime? TimeBegin { get; set; }
        public System.DateTime? TimeEnd { get; set; }
        public System.Boolean IsRowUpdate { get; set; }
        public System.Boolean IsEntity { get; set; }
        //public List<ActionEO> ActionListEO { get; set; }

        #region Конструктор

        public ActionEO()
        {
            GuidId = Guid.Empty;
            Name = "";
            Discription = "";
            IsDelete = false;
            IsActive = false;
            TimeBegin = null;
            TimeEnd = null;
            //ActionListEO = null;
            IsRowUpdate = false;
            IsEntity = false;
        }

        public ActionEO(Guid uuidId, String strName, String strDiscription, Boolean bIsDelete, Boolean bIsActive, System.DateTime dtTimeBegin, System.DateTime dtTimeEnd, System.Boolean bIsRowUpdate, System.Boolean bIsEntity)
        {
            GuidId = uuidId;
            Name = strName;
            Discription = strDiscription;
            IsDelete = bIsDelete;
            IsActive = bIsActive;
            //ActionListEO = null;
            TimeBegin = dtTimeBegin;
            TimeEnd = dtTimeEnd;
            IsRowUpdate = bIsRowUpdate;
            IsEntity = bIsEntity;
        }

        #endregion

        public List<ActionEO> GetActionListNoDelete()
        {
            List<ActionEO> ActionEOList = new List<ActionEO>();
            
            DiscountsData DisDate = new DiscountsData();
            List<T_Action> TActionList = DisDate.SelectActionNoDeleted();

            foreach (T_Action TAction in TActionList)
            {
                ActionEO actionEO = new ActionEO();
                actionEO.MapData(TAction);
                ActionEOList.Add(actionEO);
            }

            return ActionEOList;
        }

        public void MapData(T_Action TAction)
        {
            GuidId = TAction.A_Guid;
            Name = TAction.A_Name;
            Discription = TAction.A_Discription;
            IsDelete = TAction.A_IsDelete;
            IsActive = TAction.A_IsActie;
            TimeBegin = TAction.A_TimeBegin;
            TimeEnd = TAction.A_TimeEnd;
            IsEntity = TAction.A_IsEntity;
        }


        #region Insert_old

        public bool Insert(/*List<ActionEO>*/ ActionEO action)
        {
            DiscountsData disDate = new DiscountsData();

            if (!Validate(action))
            {
                return false;
            }

            //foreach (ActionEO item in action)
            //{
                T_Action tActionTmp = new T_Action();

                tActionTmp.A_Guid = (action.GuidId == System.Guid.Empty) ? System.Guid.NewGuid() : action.GuidId;   //action.GuidId
                tActionTmp.A_Name = action.Name; //.TrimStart(); // заполняем поля 
                tActionTmp.A_Discription = action.Discription;
                tActionTmp.A_IsActie = action.IsActive;
                tActionTmp.A_IsDelete = action.IsDelete;
                tActionTmp.A_TimeBegin = action.TimeBegin;
                tActionTmp.A_TimeEnd = action.TimeEnd;
                tActionTmp.A_IsEntity = action.IsEntity;

                disDate.InsertAction(tActionTmp); // добавляем объект
            //}

            disDate.SaveChanges(); // сохраняем изминения в БД

            return true;
        }

        public bool Validate(ActionEO listAction)
        {
            if (listAction == null) // /*&& (listAction.GuidId != System.Guid.Empty && !System.String.IsNullOrEmpty(listAction.GuidId.ToString()) && System.String.IsNullOrEmpty(listAction.Name) && System.String.IsNullOrEmpty(listAction.Discription))*/ 
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        #endregion

        #region Общий Save

        public bool Save(List<ActionEO> lstActionEO, List<ActionEO> lstActionEOforDel, Guid uidAction)
        {
            DiscountsData DisDate = new DiscountsData();
            try
            {
                //if (!Validate(lstDiscountCountGoodsEO))
                //{
                //    return false;
                //}

                // --- Insert и Update ---

                foreach (ActionEO item in lstActionEO)
                {
                    // если GuidId == Empty значит это новый клиент и надо сделать Insert
                    if (item.GuidId == Guid.Empty)
                    {
                        item.GuidId = Guid.NewGuid();
                        Insert(item, DisDate, uidAction);
                        DisDate.SaveChanges(); // сохраняем изминения в БД
                    }
                    else
                    {
                        // если GuidId != Empty значит это существующий клиент
                        // если item.IsRowUpdate=true значит   и надо сделать Update
                        if (item.GuidId != Guid.Empty && item.IsRowUpdate)
                        {
                            Update(item, DisDate);
                            DisDate.SaveChanges(); // сохраняем изминения в БД
                        }
                    }
                }

                // --- Delete ---

                foreach (ActionEO item in lstActionEOforDel)
                {
                    if (item.GuidId.CompareTo(System.Guid.Empty) == 0) { continue; }

                    Delete(item.GuidId, DisDate);
                    DisDate.SaveChanges(); // сохраняем изминения в БД
                }

                return true;
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                lstActionEO.Clear();
                lstActionEOforDel.Clear();
            }
        }

        #endregion

        #region Insert

        private void Insert(ActionEO item, DiscountsData disDate, System.Guid uidAction)
        {
            T_Action tAction = new T_Action();

            tAction.A_Guid = item.GuidId;
            tAction.A_Name = item.Name;
            tAction.A_Discription = item.Discription;
            tAction.A_IsActie = item.IsActive;
            tAction.A_IsDelete = item.IsDelete;
            tAction.A_TimeBegin = item.TimeBegin;
            tAction.A_TimeEnd = item.TimeEnd;
            tAction.A_IsEntity = item.IsEntity;
            // некоторые другие поля остаются незаполненными, в них должно быть значение, от конструктора по умолчанию

            disDate.InsertAction(tAction);
        }

        #endregion

        #region Update

        private void Update(ActionEO item, DiscountsData disDate)
        {
            T_Action tAction = disDate.SelectActionByUid(item.GuidId);

            tAction.A_Name = item.Name;
            tAction.A_Discription = item.Discription;
            tAction.A_IsActie = item.IsActive;
            tAction.A_IsDelete = item.IsDelete;
            tAction.A_TimeBegin = item.TimeBegin;
            tAction.A_TimeEnd = item.TimeEnd;
            tAction.A_IsEntity = item.IsEntity;
        }

        #endregion
        
        #region Delete

        private void Delete(Guid uidAction, DiscountsData disDate)
        {
            disDate.DeleteAction(uidAction);
        }

        #endregion

    }

    public class GroupEO
    {
        #region Поля

        public Guid Id { get; set; }
        public String GroupName { get; set; }
        public Guid GuidSession { get; set; }

        #endregion

        #region Констуктор

        public GroupEO()
        {
            Id = Guid.Empty;
            GroupName = "";
            GuidSession = Guid.Empty;
        }

        #endregion

        #region Select

        //public List<GroupEO> GetGroupList()
        //{
        //    List<GroupEO> GroupEOList = new List<GroupEO>();

        //    DiscountsData DisDate = new DiscountsData();
        //    List<String> strGroupList = DisDate.SelectGroupList();

        //    foreach (Ct_Group ctGroup in ctGroupList)
        //    {
        //        GroupEO groupEO = new GroupEO();
        //        groupEO.MapData(ctGroup);
        //        GroupEOList.Add(groupEO);
        //    }

        //    return GroupEOList;
        //}

        public IEnumerable GetGroupList()
        {
            DiscountsData DisDate = new DiscountsData();
            //var a = DisDate.SelectGroupList();
            return DisDate.SelectGroupList();
        }


        /// <summary>
        /// Получить List типа GroupEO
        /// </summary>
        /// <param name="strGroupString">единая строка с разделителями </param>
        /// <param name="uidSession">guid сесии</param>
        /// <returns>List типа GroupEO</returns>
        public List<GroupEO> GetGroupList(String strGroupString, Guid uidSession)
        {
            List<GroupEO> GroupEOList = new List<GroupEO>();

            if (String.IsNullOrEmpty(strGroupString))
            {
                return GroupEOList;
            }

            // конвертируем из string в List<string> разделителем строк должна быть '^'
            List<string> strListGroup = strGroupString.Split('^').ToList();

            foreach (var ctGroup in strListGroup)
            {
                GroupEO groupEO = new GroupEO();
                groupEO.MapData(ctGroup, uidSession);
                GroupEOList.Add(groupEO);
            }
            return GroupEOList;
        }

        /// <summary>
        /// Получить строку фильтров которые были использованы при поиске
        /// </summary>
        /// <param name="uidSession"></param>
        /// <returns></returns>
        public string GetPatternStrForGroup(Guid uidSession)
        {
            DiscountsData DisDate = new DiscountsData();

            string strRerurn = DisDate.SelectPatternStrForGroup(uidSession);

            if (!String.IsNullOrEmpty(strRerurn))
            {
                return strRerurn;
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// Получить строку фильтров которые были использованы при поиске
        /// </summary>
        /// <param name="uidAction"></param>
        /// <returns></returns>
        public List<string> GetListGroupName(Guid uidAction)
        {
            DiscountsData DisDate = new DiscountsData();
            List<string> lstGroupName = DisDate.SelectEntityGroupList(uidAction);

            return lstGroupName;
        }


        public void MapData(Ct_Group ctGroup)
        {
            GroupName = ctGroup.Группа;
        }

        public void MapData(String strGroup, Guid uidSession)
        {
            Id = Guid.NewGuid();
            GroupName = strGroup;
            GuidSession = uidSession;
        }

        #endregion

        public bool Save(List<GroupEO> lstGroupEO, Guid uidAction)
        {
            try
            {
                DiscountsData DisDate = new DiscountsData();
                //T_Group tGroup = new T_Group();
                int n = DisDate.SelectCountGroupByUid(uidAction);

                for (int i = 0; i <n ; i++)
                {
                    T_Group tGrp = DisDate.SelectGroupByUid(uidAction);
                    DisDate.DeleteT_Group(tGrp);
                    DisDate.SaveChanges();
                }

                int fl = 0;
                foreach (GroupEO groupEO in lstGroupEO)
                {
                    T_Group tGroup = new T_Group();

                    tGroup.Group_Guid = System.Guid.NewGuid();
                    tGroup.A_Guid = uidAction;

                    if (fl!=0)
                    {
                        string strTemp = groupEO.GroupName.Substring(0, 1);
                        if (strTemp == " ")
                        {
                            groupEO.GroupName = groupEO.GroupName.TrimStart(' ');
                        }
                    }
                    
                    tGroup.Group_Name = groupEO.GroupName;

                    DisDate.InsertT_Group(tGroup);
                    DisDate.SaveChanges();
                    fl++;
                }
                

                return true;
            }
            catch (Exception e2)
            {
                return false;
            }
        }



        #region Insert

        public bool Insert(List<GroupEO> listGroup)
        {
            if (!Validate(listGroup))
            {
                return false;
            }

            DiscountsData DisDate = new DiscountsData();
            //List<T_GroupTemp> listGrt = new List<T_GroupTemp>();

            foreach (GroupEO item in listGroup)
            {
                //listGrt.Add(new T_GroupTemp { GroupName = item.GroupName, IdSession = item.GuidSession });
                T_GroupTemp tGrTmp = new T_GroupTemp();
                tGrTmp.Id = item.Id;
                    // System.Guid.NewGuid(); // генерируем здесь, т.к. NewID() на стороне SQL сервера не срабатывает
                tGrTmp.GroupName = item.GroupName.TrimStart(); // заполняем поля 
                tGrTmp.IdSession = item.GuidSession; // заполняем поля
                DisDate.InsertT_GroupTemp(tGrTmp); // добавляем объект
            }

            DisDate.SaveChanges(); // сохраняем изминения в БД

            return true;
        }

        public bool Validate(List<GroupEO> listGroup)
        {
            if (listGroup.Count == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        #endregion

        #region Delete

        public bool Delete(List<GroupEO> listGroup)
        {
            if (!Validate(listGroup))
            {
                return false;
            }

            DiscountsData DisDate = new DiscountsData();

            foreach (GroupEO item in listGroup)
            {
                T_GroupTemp tGrTmp = new T_GroupTemp();
                tGrTmp.Id = item.Id;
                tGrTmp.GroupName = item.GroupName; // заполняем поля 
                tGrTmp.IdSession = item.GuidSession; // заполняем поля

                DisDate.DeleteT_GroupTemp(tGrTmp); //.DeleteT_GroupTemp(item);
            }

            DisDate.SaveChanges(); // сохраняем изминения в БД

            return true;
        }

        #endregion
    }



    public class SubGroupEO
    {
        #region Поля класса

        public System.Guid Id { get; set; }
        public System.String SubGroupName { get; set; }
        public System.Guid GuidSession { get; set; }

        #endregion

        #region Конструктор по умолчанию

        public SubGroupEO()
        {
            Id = System.Guid.NewGuid();
            SubGroupName = "";
            GuidSession = System.Guid.NewGuid();
        }

        #endregion

        #region Select

        public IEnumerable GetSubGroupList()
        {
            DiscountsData DisDate = new DiscountsData();
            return DisDate.SelectSubGroupList();
        }

        public List<SubGroupEO> GetSubGroupList(System.String strSubGroupString, System.Guid uidSession)
        {
            List<SubGroupEO> SubGroupEOList = new List<SubGroupEO>();

            if (System.String.IsNullOrEmpty(strSubGroupString))
            {
                return SubGroupEOList;
            }

            // конвертируем из string в List<string> разделителем строк должна быть '^'
            List<string> strListSubGroup = strSubGroupString.Split('^').ToList();

            foreach (var ctSubGroup in strListSubGroup)
            {
                SubGroupEO subgroupEO = new SubGroupEO();
                subgroupEO.MapData(ctSubGroup, uidSession);
                SubGroupEOList.Add(subgroupEO);
            }
            return SubGroupEOList;
        }

        /// <summary>
        /// Получить строку фильтров которые были использованы при поиске
        /// </summary>
        /// <param name="uidSession"></param>
        /// <returns></returns>
        public string GetPatternStrForSubGroup(System.Guid uidSession)
        {
            DiscountsData DisDate = new DiscountsData();

            string strRerurn = DisDate.SelectPatternStrForSubGroup(uidSession);

            if (!System.String.IsNullOrEmpty(strRerurn))
            {
                return strRerurn;
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// Получить строку фильтров которые были использованы при поиске
        /// </summary>
        /// <param name="uidAction"></param>
        /// <returns></returns>
        public List<string> GetListSubGroupName(Guid uidAction)
        {
            DiscountsData DisDate = new DiscountsData();
            List<string> lstSubGroupName = DisDate.SelectEntitySubGroupList(uidAction);

            return lstSubGroupName;
        }

        public void MapData(System.String strSubGroup, System.Guid uidSession)
        {
            Id = System.Guid.NewGuid();
            SubGroupName = strSubGroup;
            GuidSession = uidSession;
        }

        //public void MapData(Ct_SubGroup ctSubGroup)
        //{
        //    SubGroupName = ctSubGroup.Подгруппа;
        //}

        public bool Save(List<SubGroupEO> lstSubGroupEO, Guid uidAction)
        {
            try
            {
                DiscountsData DisDate = new DiscountsData();
                
                int n = DisDate.SelectCountSubGroupByUid(uidAction);

                for (int i = 0; i < n; i++)
                {
                    T_SubGroup tSubGrp = DisDate.SelectSubGroupByUid(uidAction);

                    DisDate.DeleteT_SubGroup(tSubGrp);
                    DisDate.SaveChanges();
                }

                int fl = 0;
                foreach (SubGroupEO subGroupEO in lstSubGroupEO)
                {
                    T_SubGroup tSubGroup = new T_SubGroup();

                    tSubGroup.SubGroup_Guid = System.Guid.NewGuid();
                    tSubGroup.A_Guid = uidAction;

                    if (fl != 0)
                    {
                        string strTemp = subGroupEO.SubGroupName.Substring(0, 1);
                        if (strTemp == " ")
                        {
                            subGroupEO.SubGroupName = subGroupEO.SubGroupName.TrimStart(' ');
                        }
                    }

                    tSubGroup.SubGroup_Name = subGroupEO.SubGroupName;

                    DisDate.InsertT_SubGroup(tSubGroup);
                    DisDate.SaveChanges();
                    fl++;
                }

                return true;
            }
            catch (Exception e2)
            {
                return false;
            }
        }


        #endregion

        #region Insert

        public bool Insert(List<SubGroupEO> listSubGroup)
        {
            DiscountsData DisDate = new DiscountsData();

            if (!Validate(listSubGroup))
            {
                return false;
            }

            foreach (SubGroupEO item in listSubGroup)
            {
                T_SubGroupTemp tSubGrTmp = new T_SubGroupTemp();

                tSubGrTmp.Id = item.Id;
                tSubGrTmp.SubGroupName = item.SubGroupName.TrimStart(); // заполняем поля 
                tSubGrTmp.IdSession = item.GuidSession; // заполняем поля
                DisDate.InsertT_SubGroupTemp(tSubGrTmp); // добавляем объект
            }

            DisDate.SaveChanges(); // сохраняем изминения в БД

            return true;
        }

        public bool Validate(List<SubGroupEO> listSubGroup)
        {
            if (listSubGroup.Count == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        #endregion 

        #region Delete

        public bool Delete(List<SubGroupEO> listSubGroup)
        {
            if (!Validate(listSubGroup))
            {
                return false;
            }

            DiscountsData DisDate = new DiscountsData();

            foreach (SubGroupEO item in listSubGroup)
            {
                T_SubGroupTemp tSubGrTmp = new T_SubGroupTemp();

                tSubGrTmp.Id = item.Id;
                tSubGrTmp.SubGroupName = item.SubGroupName; // заполняем поля 
                tSubGrTmp.IdSession = item.GuidSession; // заполняем поля

                DisDate.DeleteT_SubGroupTemp(tSubGrTmp); // 'помечаем' на удаление
            }

            DisDate.SaveChanges(); // сохраняем изминения в БД

            return true;
        }

        #endregion 
    }

    public class TrademarkEO
    {
        #region Поля

        public Guid Id { get; set; }
        public String TrademarkName { get; set; }
        public Guid GuidSession { get; set; }

        #endregion

        #region Конструктор

        public TrademarkEO()
        {
            Id = Guid.NewGuid();
            TrademarkName = "";
            GuidSession = Guid.NewGuid();
        }

        #endregion

        #region Select

        public IEnumerable GetTradeMarkList()
        {
            DiscountsData DisDate = new DiscountsData();
            return DisDate.SelectTradeMarkList();
        }

        public List<TrademarkEO> GetTradeMarkList(String strTrademarkString, Guid uidSession)
        {
            List<TrademarkEO> TrademarkEOList = new List<TrademarkEO>();

            if (String.IsNullOrEmpty(strTrademarkString))
            {
                return TrademarkEOList;
            }

            // конвертируем из string в List<string> разделителем строк должна быть '^'
            List<string> strListTrademark = strTrademarkString.Split('^').ToList();

            foreach (var ctTrademark in strListTrademark)
            {
                TrademarkEO trademarkEO = new TrademarkEO();
                trademarkEO.MapData(ctTrademark, uidSession);
                TrademarkEOList.Add(trademarkEO);
            }
            return TrademarkEOList;
        }

        /// <summary>
        /// Получить строку фильтров которые были использованы при поиске
        /// </summary>
        /// <param name="uidSession"></param>
        /// <returns></returns>
        public string GetPatternTradeMark(Guid uidSession)
        {
            DiscountsData DisDate = new DiscountsData();

            string strRerurn = DisDate.SelectPatternTradeMark(uidSession);

            if (!String.IsNullOrEmpty(strRerurn))
            {
                return strRerurn;
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// Получить строку фильтров которые были использованы при поиске
        /// </summary>
        /// <param name="uidAction"></param>
        /// <returns></returns>
        public List<string> GetListTrademarkName(Guid uidAction)
        {
            DiscountsData DisDate = new DiscountsData();
            List<string> lstTrademarkName = DisDate.SelectEntityTrademarkList(uidAction);

            return lstTrademarkName;
        }

        public void MapData(String strTrademark, Guid uidSession)
        {
            Id = Guid.NewGuid();
            TrademarkName = strTrademark;
            GuidSession = uidSession;
        }

        public bool Save(List<TrademarkEO> lstTrademarkEO, Guid uidAction)
        {
            try
            {
                DiscountsData DisDate = new DiscountsData();

                int n = DisDate.SelectCountTradeMarkByUid(uidAction);

                for (int i = 0; i < n; i++)
                {
                    T_TradeMark tTradeMark = DisDate.SelectTradeMarkByUid(uidAction);

                    DisDate.DeleteT_TradeMark(tTradeMark);
                    DisDate.SaveChanges();
                }

                int fl = 0;
                foreach (TrademarkEO trademarkEO in lstTrademarkEO)
                {
                    T_TradeMark tTradeMark = new T_TradeMark();

                    tTradeMark.Trademark_Guid = System.Guid.NewGuid();
                    tTradeMark.A_Guid = uidAction;

                    if (fl != 0)
                    {
                        string strTemp = trademarkEO.TrademarkName.Substring(0, 1);
                        if (strTemp == " ")
                        {
                            trademarkEO.TrademarkName = trademarkEO.TrademarkName.TrimStart(' ');
                        }
                    }

                    tTradeMark.Trademark_Name = trademarkEO.TrademarkName;

                    DisDate.InsertT_TradeMark(tTradeMark);
                    DisDate.SaveChanges();
                    fl++;
                }

                return true;
            }
            catch (Exception e2)
            {
                return false;
            }
        }

        #endregion

        #region Insert

        public bool Insert(List<TrademarkEO> listTrademark)
        {
            DiscountsData DisDate = new DiscountsData();

            if (!Validate(listTrademark))
            {
                return false;
            }

            foreach (TrademarkEO item in listTrademark)
            {
                T_TradeMarkTemp tTmTmp = new T_TradeMarkTemp();
                tTmTmp.Id = item.Id;
                tTmTmp.TradeMark = item.TrademarkName.TrimStart();
                ; // заполняем поля 
                tTmTmp.IdSession = item.GuidSession; // заполняем поля
                DisDate.InsertT_TradeMarkTemp(tTmTmp); // добавляем объект
            }

            DisDate.SaveChanges(); // сохраняем изминения в БД

            return true;
        }

        public bool Validate(List<TrademarkEO> listTrademark)
        {
            if (listTrademark.Count == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        #endregion

        #region Delete

        public bool Delete(List<TrademarkEO> listTrademark)
        {
            if (!Validate(listTrademark))
            {
                return false;
            }

            DiscountsData DisDate = new DiscountsData();

            foreach (TrademarkEO item in listTrademark)
            {
                T_TradeMarkTemp tTmTmp = new T_TradeMarkTemp();
                tTmTmp.Id = item.Id;
                tTmTmp.TradeMark = item.TrademarkName; // заполняем поля 
                tTmTmp.IdSession = item.GuidSession; // заполняем поля

                DisDate.DeleteT_TradeMarkTemp(tTmTmp); // 'помечаем' на удаление
            }

            DisDate.SaveChanges(); // сохраняем изминения в БД

            return true;
        }

        #endregion
    }

    public class LineEO
    {
        #region Поля

        public Guid Id { get; set; }
        public String LineName { get; set; }
        public Guid GuidSession { get; set; }

        #endregion

        #region Конструктор

        public LineEO()
        {
            Id = Guid.NewGuid();
            LineName = "";
            GuidSession = Guid.NewGuid();
        }

        #endregion

        #region Select

        public IEnumerable GetLineList()
        {
            DiscountsData DisDate = new DiscountsData();
            return DisDate.SelectLineList();
        } 

        /*
        public List<string> GetLineList()
        {
            DiscountsData DisDate = new DiscountsData();
            return DisDate.SelectLineList();
        }
        */

        public List<LineEO> GetLineList(String strLineString, Guid uidSession)
        {
            List<LineEO> LineEOList = new List<LineEO>();

            if (String.IsNullOrEmpty(strLineString))
            {
                return LineEOList;
            }

            // конвертируем из string в List<string> разделителем строк должна быть '^'
            List<string> strListLine = strLineString.Split('^').ToList();

            foreach (var ctLine in strListLine)
            {
                LineEO lineEO = new LineEO();
                lineEO.MapData(ctLine, uidSession);
                LineEOList.Add(lineEO);
            }
            return LineEOList;
        }


        /// <summary>
        /// Получить строку фильтров которые были использованы при поиске
        /// </summary>
        /// <param name="uidSession"></param>
        /// <returns></returns>
        public string GetPatternLine(Guid uidSession)
        {
            DiscountsData DisDate = new DiscountsData();

            string strRerurn = DisDate.SelectPatternLine(uidSession);

            if (!String.IsNullOrEmpty(strRerurn))
            {
                return strRerurn;
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// Получить строку фильтров которые были использованы при поиске
        /// </summary>
        /// <param name="uidAction"></param>
        /// <returns></returns>
        public List<string> GetListLineName(Guid uidAction)
        {
            DiscountsData DisDate = new DiscountsData();
            List<string> lstLineName = DisDate.SelectEntityLineList(uidAction);

            return lstLineName;
        }


        public void MapData(String strLine, Guid uidSession)
        {
            Id = Guid.NewGuid();
            LineName = strLine;
            GuidSession = uidSession;
        }

        public bool Save(List<LineEO> lstLineEO, Guid uidAction)
        {
            try
            {
                DiscountsData DisDate = new DiscountsData();

                int n = DisDate.SelectCountLineByUid(uidAction);

                for (int i = 0; i < n; i++)
                {
                    T_Line tLine = DisDate.SelectLineByUid(uidAction);

                    DisDate.DeleteT_Line(tLine);
                    DisDate.SaveChanges();
                }

                int fl = 0;
                foreach (LineEO lineEO in lstLineEO)
                {
                    T_Line tLine = new T_Line();

                    tLine.Line_Guid = System.Guid.NewGuid();
                    tLine.A_Guid = uidAction;

                    if (fl != 0)
                    {
                        string strTemp = lineEO.LineName.Substring(0, 1);
                        if (strTemp == " ")
                        {
                            lineEO.LineName = lineEO.LineName.TrimStart(' ');
                        }
                    }

                    tLine.Line_Name = lineEO.LineName;

                    DisDate.InsertT_Line(tLine);
                    DisDate.SaveChanges();
                    fl++;
                }

                return true;
            }
            catch (Exception e2)
            {
                return false;
            }
        }

        #endregion

        #region Insert

        public bool Insert(List<LineEO> listLine)
        {
            DiscountsData DisDate = new DiscountsData();

            if (!Validate(listLine))
            {
                return false;
            }

            foreach (LineEO item in listLine)
            {
                T_LineTemp tLnTmp = new T_LineTemp();
                tLnTmp.Id = item.Id;
                tLnTmp.Line = item.LineName.TrimStart();
                ; // заполняем поля 
                tLnTmp.IdSession = item.GuidSession; // заполняем поля
                DisDate.InsertT_LineTemp(tLnTmp); // добавляем объект
            }

            DisDate.SaveChanges(); // сохраняем изминения в БД

            return true;
        }

        public bool Validate(List<LineEO> listLine)
        {
            if (listLine.Count == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        #endregion

        #region Delete

        public bool Delete(List<LineEO> listLine)
        {
            if (!Validate(listLine))
            {
                return false;
            }

            DiscountsData DisDate = new DiscountsData();

            foreach (LineEO item in listLine)
            {
                T_LineTemp tLnTmp = new T_LineTemp();
                tLnTmp.Id = item.Id;
                tLnTmp.Line = item.LineName; // заполняем поля 
                tLnTmp.IdSession = item.GuidSession; // заполняем поля

                DisDate.DeleteT_LineTemp(tLnTmp); // 'помечаем' на удаление
            }

            DisDate.SaveChanges(); // сохраняем изминения в БД

            return true;
        }

        #endregion    
    }

    public class InternalGroupEO
    {
        #region Поля класса
        
        public System.Guid Id { get; set; }
        public System.Int32 GroupId { get; set; }
        //public System.Int32 GroupNo { get; set; }
        //public System.String GroupName { get; set; }
        public System.Guid GuidSession { get; set; }

        #endregion

        #region Конструктор по умолчанию

        public InternalGroupEO()
        {
            Id = System.Guid.NewGuid();
            GroupId = 0;
            GuidSession = System.Guid.NewGuid();
        }

        #endregion

        #region Select

        public IEnumerable GetInternalGroupList()
        {
            DiscountsData DisDate = new DiscountsData();
            return DisDate.SelectInternalGroupList();
        }

        public List<InternalGroupEO> GetInternalGroupList(System.String strInternalGroupString, System.Guid uidSession)
        {
            List<InternalGroupEO> InternalGroupEOList = new List<InternalGroupEO>();

            if (System.String.IsNullOrEmpty(strInternalGroupString))
            {
                return InternalGroupEOList;
            }

            // конвертируем из string в List<string> разделителем строк должна быть '^'
            List<string> strListInternalGroup = strInternalGroupString.Split('^').ToList();

            foreach (string strInternalGroup in strListInternalGroup)
            {
                InternalGroupEO intGrEO = new InternalGroupEO();
                intGrEO.MapData(strInternalGroup, uidSession);
                InternalGroupEOList.Add(intGrEO);
            }
            return InternalGroupEOList;
        }

        public void MapData(System.String strIntGroup, System.Guid uidSession)
        {
            Id = System.Guid.NewGuid();
            GroupId =Convert.ToInt32(strIntGroup.TrimStart());
            GuidSession = uidSession;
        }

        /// <summary>
        /// Получить строку фильтров которые были использованы при поиске
        /// </summary>
        /// <param name="uidSession"></param>
        /// <returns></returns>
        public string GetPatternInternalGroup(Guid uidSession)
        {
            DiscountsData DisDate = new DiscountsData();

            string strRerurn = DisDate.SelectPatternInternalGroup(uidSession);

            if (!String.IsNullOrEmpty(strRerurn))
            {
                return strRerurn;
            }
            else
            {
                return "";
            }
        }

        #endregion

        #region Insert

        public bool Insert(List<InternalGroupEO> listInternalGroup)
        {
            DiscountsData DisDate = new DiscountsData();

            if (!Validate(listInternalGroup))
            {
                return false;
            }

            foreach (InternalGroupEO item in listInternalGroup)
            {
                T_InternalGroupTemp tInternalGrTmp = new T_InternalGroupTemp();

                tInternalGrTmp.Id = item.Id;
                tInternalGrTmp.Group_Id = item.GroupId; //.TrimStart(); // заполняем поля 
                tInternalGrTmp.IdSession = item.GuidSession; // заполняем поля
                DisDate.InsertT_InternalGroupTemp(tInternalGrTmp); // добавляем объект
            }

            DisDate.SaveChanges(); // сохраняем изминения в БД

            return true;
        }

        public bool Validate(List<InternalGroupEO> listInternalGroup)
        {
            if (listInternalGroup.Count == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        #endregion

        #region Delete

        public bool Delete(List<InternalGroupEO> listInternalGroup)
        {
            if (!Validate(listInternalGroup))
            {
                return false;
            }

            DiscountsData DisDate = new DiscountsData();

            foreach (InternalGroupEO item in listInternalGroup)
            {
                T_InternalGroupTemp tInternalGrTmp = new T_InternalGroupTemp();

                tInternalGrTmp.Id = item.Id;
                tInternalGrTmp.Group_Id = item.GroupId; // заполняем поля 
                tInternalGrTmp.IdSession = item.GuidSession; // заполняем поля

                DisDate.DeleteT_InternalGroupTemp(tInternalGrTmp); // 'помечаем' на удаление
            }

            DisDate.SaveChanges(); // сохраняем изминения в БД

            return true;
        }

        #endregion 

    }

    public class ProducerEO
    {
        #region Поля класса

        public System.Guid Id { get; set; }
        public System.Int32 ProducerId { get; set; }
        public System.Guid GuidSession { get; set; }
        public System.Guid ProducerUid { get; set; }

        #endregion

        #region Конструктор по умолчанию

        public ProducerEO()
        {
            Id = System.Guid.NewGuid();
            ProducerId = 0;
            GuidSession = System.Guid.NewGuid();
            ProducerUid = Guid.Empty;
        }

        #endregion

        #region Select

        public IEnumerable GetProducerList()
        {
            DiscountsData DisDate = new DiscountsData();
            return DisDate.SelectProducerList();
        }

        public List<ProducerEO> GetProducerList(System.String strProducerString, System.Guid uidSession)
        {
            List<ProducerEO> ProducerEOList = new List<ProducerEO>();
            DiscountsData DisDate = new DiscountsData();

            if (System.String.IsNullOrEmpty(strProducerString))
            {
                return ProducerEOList;
            }

            // конвертируем из string в List<string> разделителем строк должна быть '^'
            List<string> strListProducer = strProducerString.Split('^').ToList();

            foreach (string strProducer in strListProducer)
            {
                ProducerEO intGrEO = new ProducerEO();
                intGrEO.MapData(strProducer, uidSession, DisDate);
                ProducerEOList.Add(intGrEO);
            }
            return ProducerEOList;
        }

        public void MapData(System.String strIntGroup, System.Guid uidSession, DiscountsData DisDate)
        {
            Id = System.Guid.NewGuid(); 
            ProducerUid = Guid.Parse(strIntGroup.TrimStart());

            if (ProducerUid!=Guid.Empty)
            {
                ProducerId = DisDate.SelectProducerIdByUid(ProducerUid); // здесь находим Id по Uid
            }
            GuidSession = uidSession;
        }

        /// <summary>
        /// Получить строку фильтров которые были использованы при поиске
        /// </summary>
        /// <param name="uidAction"></param>
        /// <returns></returns>
        public List<Guid> GetListProducerName(Guid uidAction)
        {
            DiscountsData DisDate = new DiscountsData();
            List<Guid> lstProducerName = DisDate.SelectEntityProducerList(uidAction);

            return lstProducerName;
        }

        /// <summary>
        /// Получить строку фильтров которые были использованы при поиске
        /// </summary>
        /// <param name="uidSession"></param>
        /// <returns></returns>
        public string GetPatternProducer(Guid uidSession)
        {
            DiscountsData DisDate = new DiscountsData();

            string strRerurn = DisDate.SelectPatternProducer(uidSession);

            if (!String.IsNullOrEmpty(strRerurn))
            {
                return strRerurn;
            }
            else
            {
                return "";
            }
        }
        
        
        public bool Save(List<ProducerEO> lstProducerEO, Guid uidAction)
        {
            try
            {
                DiscountsData DisDate = new DiscountsData();

                int n = DisDate.SelectCountProducerByUid(uidAction);

                for (int i = 0; i < n; i++)
                {
                    T_Producer tProducer = DisDate.SelectProducerByUid(uidAction);

                    DisDate.DeleteT_Producer(tProducer);
                    DisDate.SaveChanges();
                }

                foreach (ProducerEO producerEO in lstProducerEO)
                {
                    T_Producer tProducer = new T_Producer();

                    tProducer.Producer_Guid = System.Guid.NewGuid();
                    tProducer.A_Guid = uidAction;

                    tProducer.Producer_Uid = producerEO.ProducerUid;

                    DisDate.InsertT_Producer(tProducer);
                    DisDate.SaveChanges();
                }

                return true;
            }
            catch (Exception e2)
            {
                return false;
            }
        }
        
        #endregion

        #region Insert

        public bool Insert(List<ProducerEO> listProducer)
        {
            DiscountsData DisDate = new DiscountsData();

            if (!Validate(listProducer))
            {
                return false;
            }

            foreach (ProducerEO item in listProducer)
            {
                T_ProducerTemp tProducerTmp = new T_ProducerTemp();

                tProducerTmp.Id = item.Id;
                tProducerTmp.Producer_Id = item.ProducerId; //.TrimStart(); // заполняем поля 
                tProducerTmp.IdSession = item.GuidSession; // заполняем поля
                DisDate.InsertT_ProducerTemp(tProducerTmp); // добавляем объект
            }

            DisDate.SaveChanges(); // сохраняем изминения в БД

            return true;
        } 

        public bool Validate(List<ProducerEO> listProducer)
        {
            if (listProducer.Count == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        #endregion

        #region Delete

        public bool Delete(List<ProducerEO> listProducer)
        {
            if (!Validate(listProducer))
            {
                return false;
            }

            DiscountsData DisDate = new DiscountsData();

            foreach (ProducerEO item in listProducer)
            {
                T_ProducerTemp tProducerTmp = new T_ProducerTemp();

                tProducerTmp.Id = item.Id;
                tProducerTmp.Producer_Id = item.ProducerId; // заполняем поля 
                tProducerTmp.IdSession = item.GuidSession; // заполняем поля

                DisDate.DeleteT_ProducerTemp(tProducerTmp); // 'помечаем' на удаление
            }

            DisDate.SaveChanges(); // сохраняем изминения в БД

            return true;
        }

        #endregion 
    }

    public class PreSelectdProductEO
    {
        #region Поля класса

        public List<whGood> listwhGood { get; set; }
        public whGood wh_Good { get; set; }

        //List<whGood> lstGood = new List<whGood>();

        #endregion

        #region Select

        public IQueryable GetPreSelectdProduct(Guid uidSession, bool bIsStock)
        {
            DiscountsData DisDate = new DiscountsData();
            return DisDate.SelectPreSelectdProduct(uidSession, bIsStock);
        }

        public IQueryable GetDTSourceWhiteCheckAllPosition(IQueryable dtSource, Boolean bCheck)
        {

            // данные внутри IQueryable нельзя редактировать, поэтому конвертирую данные в List. В List они доступны для редактирования
            List<whGood> listWhGood = dtSource.Cast<whGood>().ToList();


            foreach (whGood item in listWhGood)
            {
                item.whGood_Sel = (bCheck) ? true : false;
            }

            return listWhGood.AsQueryable();
        }

        public IQueryable GetListPosition(IQueryable dtSource)
        {
            // Здесь обязательно нужно выполнить проиежуточную конвертацию через List<whGood>
            List<whGood> listWhGood = dtSource.Cast<whGood>().ToList();
            return listWhGood.AsQueryable();
        }

        private void GetUsedPosition(IQueryable dtSource)
        {
            
        }

        public List<whGood> GetPreSelectdProductList(Guid uidSession, bool bIsStock)
        {
            DiscountsData DisDate = new DiscountsData();
            return DisDate.SelectPreSelectdProduct(uidSession, bIsStock).Cast<whGood>().ToList();
        }

        public List<whGood> GetGoodByAction(Guid uidAction)
        {
            DiscountsData DisDate = new DiscountsData();
            //var d = DisDate.SelectGoodByAction(uidAction).Cast<whGood>().ToList();
            return DisDate.SelectGoodByAction(uidAction).Cast<whGood>().ToList();
        }

        #endregion

        public bool Insert(List<PreSelectdProductEO> listPreSelProduct)
        {
            DiscountsData DisDate = new DiscountsData();

            if (!Validate(listPreSelProduct))
            {
                return false;
            }

            foreach (var item in listPreSelProduct)
            {
                whGood tWhGood = new whGood();

                tWhGood = item.wh_Good;

                DisDate.InsertWhGood(tWhGood);
            }
            // ***
            DisDate.SaveChanges(); // сохраняем изминения в БД

            return true;
        }

        public bool Validate(List<PreSelectdProductEO> listPreSelProduct)
        {
            if (listPreSelProduct.Count == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }


        //public IQueryable GetSelectList()
        //{
        //    var u = obj;
        //    listwhGood.Add(good);
        //    lstGood.Add(whGood(u));
        //}
    }

    public class GoodDiscountLinkEO
    {
        //public List<T_GoodDiscountLink> lstGDL { get; set; } 

        public System.Guid GDL_Guid { get; set; }
        public System.Guid whGood_Uid { get; set; }
        public System.Int64 whGood_Id { get; set; }
        //public System.Guid D_Guid { get; set; }
        public System.Guid A_Guid { get; set; }

        public GoodDiscountLinkEO()
        {
            GDL_Guid = System.Guid.NewGuid();
            whGood_Uid = Guid.Empty;
            whGood_Id = 0;
            //D_Guid = Guid.Empty; // System.Guid.NewGuid();
            A_Guid = Guid.Empty;
            //lstGDL = null;
        }

        #region Select

        public IQueryable GetGoodDiscountLinkItem(Guid uid)
        {
            DiscountsData DisDate = new DiscountsData();
            return DisDate.SelectGoodDiscountLink(uid);
        }

        public IQueryable GetGoodDiscountLinkAndActionName()
        {
            DiscountsData DisDate = new DiscountsData();
            return DisDate.SelectGoodDiscountLinkAndActionName();
        }

        

        #endregion

        #region Insert

        public bool Insert(List<GoodDiscountLinkEO> listGoodDiscountLink)
        {
            DiscountsData DisDate = new DiscountsData();

            if (!Validate(listGoodDiscountLink))
            {
                return false;
            }

            foreach (GoodDiscountLinkEO item in listGoodDiscountLink)
            {
                T_GoodDiscountLink tGoodDiscountLink = new T_GoodDiscountLink();

                tGoodDiscountLink.GDL_Guid = item.GDL_Guid;
                tGoodDiscountLink.whGood_Id = item.whGood_Id;
                tGoodDiscountLink.whGood_Uid = item.whGood_Uid;
                //tGoodDiscountLink.D_Guid = item.D_Guid;
                tGoodDiscountLink.A_Guid = item.A_Guid;

                DisDate.InsertT_GoodDiscountLink(tGoodDiscountLink); // добавляем объект


                // Добавление данных в T_GoodSupplyLink
                // не используется с 25.05.2013
                /*
                List<System.Int32> litWhSupplyId;
                litWhSupplyId=DisDate.GetSupplyIdByWhGoodId(Convert.ToInt32(tGoodDiscountLink.whGood_Id));

                foreach (System.Int32 i in litWhSupplyId)
                {
                    T_GoodSupplyLink tGoodSupplyLink = new T_GoodSupplyLink();

                    tGoodSupplyLink.Gsl_Guid = System.Guid.NewGuid();
                    tGoodSupplyLink.Gdl_Guid = item.GDL_Guid;
                    tGoodSupplyLink.whSupply_Id = i;

                    DisDate.InsertT_GoodSupplyLink(tGoodSupplyLink);
                }
                */

            }

            DisDate.SaveChanges(); // сохраняем изминения в БД

            return true;
        }

        public bool Validate(List<GoodDiscountLinkEO> listGoodDiscountLink)
        {
            if (listGoodDiscountLink.Count == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        public bool Validate(List<Guid> listUid)
        {
            if (listUid.Count == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        #endregion

        #region Delete

        //public bool Delete(List<GoodDiscountLinkEO> listGoodDiscountLink)
        //{
        //    if (!Validate(listGoodDiscountLink))
        //    {
        //        return false;
        //    }

        //    DiscountsData DisDate = new DiscountsData();

        //    foreach (GoodDiscountLinkEO item in listGoodDiscountLink)
        //    {
        //        T_GoodDiscountLink tGoodDiscountLink = new T_GoodDiscountLink();

        //        tGoodDiscountLink.GDL_Guid = item.GDL_Guid;
        //        tGoodDiscountLink.whGood_Id = item.whGood_Id;
        //        tGoodDiscountLink.whGood_Uid = item.whGood_Uid;
        //        //tGoodDiscountLink.D_Guid = item.D_Guid;
        //        tGoodDiscountLink.A_Guid = item.A_Guid;

        //        DisDate.DeleteT_GoodDiscountLink(tGoodDiscountLink); // удаляем объект
        //    }

        //    DisDate.SaveChanges(); // сохраняем изминения в БД

        //    return true;
        //}

        public bool Delete(List<Guid> lstUid)
        {
            try
            {
                if (!Validate(lstUid))
                {
                    return false;
                }

                DiscountsData DisDate = new DiscountsData();

                foreach (Guid item in lstUid)
                {
                    DisDate.DeleteT_GoodDiscountLink(item);
                    
                    // удаление из T_GoodSupplyLink
                    // не используется с 25.05.2013
                    //DisDate.DeleteT_GoodSupplyLink(DisDate.GetGdlUidByWhGoodUid(item));  
                }

                DisDate.SaveChanges(); // сохраняем изминения в БД

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        #endregion

    }

    public class PharmacyEO
    {
        #region Поля класса

        public Guid Id { get; set; }
        public String Name { get; set; }

        #endregion

        #region Конструктор

        public PharmacyEO()
        {
            Id = Guid.Empty;
            Name = String.Empty;
        }

        public PharmacyEO(Guid uid, String strName)
        {
            Id = uid;
            Name = strName;
        }

        #endregion

        //public IEnumerable GetPharmacyList()
        //{
        //    DiscountsData DisDate = new DiscountsData();
        //    return DisDate.SelectPharmacyList();
        //}

        public List<PharmacyEO> GetPharmacyList()
        {
            DiscountsData DisDate = new DiscountsData();

            List<PharmacyEO> lstPharmacyEO = new List<PharmacyEO>();

            foreach (T_Pharmacy item in DisDate.SelectPharmacyList())
            {
                lstPharmacyEO.Add(new PharmacyEO(item.Pharmacy_Guid, item.Pharmacy_Name));
            }

            return lstPharmacyEO;

        }

        public IEnumerable GetPharmacyList(System.Guid uid)
        {
            DiscountsData DisDate = new DiscountsData();
            return DisDate.SelectPharmacyList(uid);
        }

        public List<Guid> GetPatternGuidForPharmacy(System.Guid uid)
        {
            DiscountsData DisDate = new DiscountsData();
            return DisDate.SelectPatternGuidForPharmacy(uid);
        }

    }

    public class PharmacyLinkEO
    {
        #region Поля класса

        public Guid PDLL_Guid { get; set; }
        public Guid Pharmacy_Guid { get; set; }
        public Guid A_Guid { get; set; }
        //public System.Guid Temp_Guid { get; set; }

        #endregion

        #region Конструктор

        public PharmacyLinkEO()
        {
            PDLL_Guid = Guid.Empty;
            Pharmacy_Guid = Guid.Empty;
            A_Guid = Guid.Empty;
            //Temp_Guid = System.Guid.Empty;
        }

        public PharmacyLinkEO(Guid gPDLL_Guid, Guid gPharmacy_Guid, Guid gA_Guid
            /*, System.Guid gTemp_guid*/)
        {
            PDLL_Guid = gPDLL_Guid;
            Pharmacy_Guid = gPharmacy_Guid;
            A_Guid = gA_Guid;
            //Temp_Guid = gTemp_guid;
        }

        #endregion

        #region Insert

        public bool Insert(List<PharmacyLinkEO> listPharmacyLink)
        {
            int fl = 0;
            DiscountsData DisDate = new DiscountsData();

            if (!Validate(listPharmacyLink))
            {
                return false;
            }

            foreach (PharmacyLinkEO item in listPharmacyLink)
            {
                // если такой записи ещё нет в таблице
                if (!DisDate.IfExistsByPharmAndAction(item.Pharmacy_Guid, item.A_Guid))
                {
                    T_PharmDiscountLinkLink tPharmDiscountLinkLink = new T_PharmDiscountLinkLink();

                    tPharmDiscountLinkLink.PDLL_Guid = item.PDLL_Guid;
                    tPharmDiscountLinkLink.Pharmacy_Guid = item.Pharmacy_Guid;
                    tPharmDiscountLinkLink.A_Guid = item.A_Guid;

                    DisDate.InsertT_PharmDiscountLinkLink(tPharmDiscountLinkLink); // добавляем объект
                    fl++;
                }  
            }

            if (fl > 0)
            {
                DisDate.SaveChanges(); // сохраняем изминения в БД
            }
            
            listPharmacyLink.Clear();

            return true;
        }

        public bool Validate(List<PharmacyLinkEO> listPharmacyLink)
        {
            if (listPharmacyLink.Count == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        #endregion

        #region Delete

        public bool Delete(List<PharmacyLinkEO> listPharmacyLink)
        {
            int fl=0;
            DiscountsData DisDate = new DiscountsData();

            if (!Validate(listPharmacyLink))
            {
                return false;
            }

            foreach (PharmacyLinkEO item in listPharmacyLink)
            {
                // если такая запись есть в таблице
                if (DisDate.IfExistsByPharmAndAction(item.Pharmacy_Guid, item.A_Guid))
                {
                    T_PharmDiscountLinkLink tPharmDiscountLinkLink = new T_PharmDiscountLinkLink();

                    Guid uidPdll = System.Guid.Empty;
                    uidPdll=DisDate.GetPDllGuidByActionAndPharm(item.Pharmacy_Guid, item.A_Guid);
                    if (uidPdll == System.Guid.Empty) { return false; }

                    tPharmDiscountLinkLink.PDLL_Guid = uidPdll; //item.PDLL_Guid; // этот параметр (item.PDLL_Guid) неправильный сюда подставляется случайно сгенерированный GUID 
                    tPharmDiscountLinkLink.Pharmacy_Guid = item.Pharmacy_Guid;
                    tPharmDiscountLinkLink.A_Guid = item.A_Guid;

                    DisDate.DeleteT_PharmDiscountLinkLink(tPharmDiscountLinkLink); // удаляем объект
                    fl++;
                }          
            }

            if (fl > 0)
            {
                DisDate.SaveChanges(); // сохраняем изминения в БД
            }

            listPharmacyLink.Clear();
           
            return true;
        }
        
        /// <summary>
        /// Удалить дубликаты
        /// </summary>
        /// <param name="listPharmacyLink"></param>
        /// <returns></returns>
        public List<PharmacyLinkEO> RemoveDuplicate(List<PharmacyLinkEO> listPharmacyLink)
        {
            listPharmacyLink = (from o in listPharmacyLink
                                  orderby o.Pharmacy_Guid, o.A_Guid
                                  group o by o.Pharmacy_Guid into g
                                  select g.First()
                                 ).ToList();

            return listPharmacyLink;
        }


        #endregion
    }

    /// <summary>
    /// Класс скидок по количеству
    /// </summary>
    public class DiscountCountGoodsEO
    {

        #region Поля класса

        public Guid Dcg_Guid { get; set; }
        public Int32 Dcg_CountValueMin { get; set; }
        public Int32 Dcg_CountValueMax { get; set; }
        public Double Dcg_PercentDiscount { get; set; }
        public Boolean Dcg_IsActive { get; set; }
        public List<LinkDcgEO> lstLinkDcgEO { get; set; }
        public Boolean bIsUpdate { get; set; }

        #endregion

        #region Конструктор

        public DiscountCountGoodsEO()
        {
            Dcg_Guid = Guid.Empty;
            Dcg_CountValueMin = 0;
            Dcg_CountValueMax = 0;
            Dcg_PercentDiscount = 0.0;
            Dcg_IsActive = false;
            lstLinkDcgEO = null;
            bIsUpdate = false;
        }

        public DiscountCountGoodsEO(Guid uisDcg_Guid, Int32 iDcg_CountValueMin, Int32 iDcg_CountValueMax,
                                    double dDcg_PercentDiscount, bool bDcg_IsActive, List<LinkDcgEO> lstLinkDcgEO,
                                    bool bIsUpdate)
        {
            Dcg_Guid = uisDcg_Guid;
            Dcg_CountValueMin = iDcg_CountValueMin;
            Dcg_CountValueMax = iDcg_CountValueMax;
            Dcg_PercentDiscount = dDcg_PercentDiscount;
            Dcg_IsActive = bDcg_IsActive;
            this.lstLinkDcgEO = lstLinkDcgEO;
            this.bIsUpdate = bIsUpdate;
        }

        #endregion

        #region Select

        /// <summary>
        /// Получить скидки (T_DiscountCountGoods) по GUID акции 
        /// </summary>
        /// <param name="uid">GUID акции </param>
        /// <returns>List DiscountCountGoodsEO </returns>
        public List<DiscountCountGoodsEO> GetDiscountCountByAction(Guid uid)
        {
            DiscountsData DisDate = new DiscountsData();

            List<DiscountCountGoodsEO> lstDiscountCountGoodsEO = new List<DiscountCountGoodsEO>();

            foreach (T_DiscountCountGoods item in DisDate.SelectDiscountCountByAction(uid))
            {
                lstDiscountCountGoodsEO.Add(new DiscountCountGoodsEO(item.Dcg_Guid, item.Dcg_CountValueMin,
                                                                     item.Dcg_CountValueMax, item.Dcg_PercentDiscount,
                                                                     item.Dcg_IsActive, null, false));
            }

            return lstDiscountCountGoodsEO;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public DiscountCountGoodsEO GetDiscountCountById(Guid uid)
        {
            DiscountsData DisDate = new DiscountsData();
            DiscountCountGoodsEO tDiscountCountGoodsEO = new DiscountCountGoodsEO();

            T_DiscountCountGoods tDiscountCountGoods = DisDate.SelectDiscountCountByUid(uid);

            tDiscountCountGoodsEO.Dcg_Guid = tDiscountCountGoods.Dcg_Guid;
            tDiscountCountGoodsEO.Dcg_CountValueMin = tDiscountCountGoods.Dcg_CountValueMin;
            tDiscountCountGoodsEO.Dcg_CountValueMax = tDiscountCountGoods.Dcg_CountValueMax;
            tDiscountCountGoodsEO.Dcg_PercentDiscount = tDiscountCountGoods.Dcg_PercentDiscount;
            tDiscountCountGoodsEO.Dcg_IsActive = tDiscountCountGoods.Dcg_IsActive;

            return tDiscountCountGoodsEO;
        }

        #endregion

        #region Общий Save

        public bool Save(List<DiscountCountGoodsEO> lstDiscountCountGoodsEO,List<DiscountCountGoodsEO> lstDiscountCountGoodsEOforDel,  Guid uidAction)
        {
            DiscountsData DisDate = new DiscountsData();
            try
            {
                //if (!Validate(lstDiscountCountGoodsEO))
                //{
                //    return false;
                //}

                // --- Insert и Update ---

                foreach (DiscountCountGoodsEO item in lstDiscountCountGoodsEO)
                {
                    // если Dcg_Guid == Empty значит это новый клиент и надо сделать Insert
                    if (item.Dcg_Guid == Guid.Empty)
                    {
                        item.Dcg_Guid = Guid.NewGuid();
                        Insert(item, DisDate, uidAction);
                        DisDate.SaveChanges(); // сохраняем изминения в БД
                    }
                    else
                    {
                        // если Dcg_Guid != Empty значит это существующий клиент
                        // если item.bIsUpdate=true значит   и надо сделать Update
                        if (item.Dcg_Guid != Guid.Empty && item.bIsUpdate)
                        {
                            Update(item, DisDate);
                            DisDate.SaveChanges(); // сохраняем изминения в БД
                        }
                    }
                }

                // --- Delete ---

                foreach (DiscountCountGoodsEO item in lstDiscountCountGoodsEOforDel)
                {
                    if (item.Dcg_Guid.CompareTo(System.Guid.Empty) == 0) { continue; }
                    
                    Delete(item.Dcg_Guid, uidAction, DisDate);
                    DisDate.SaveChanges(); // сохраняем изминения в БД
                }

                return true;
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                lstDiscountCountGoodsEOforDel.Clear();
                lstDiscountCountGoodsEO.Clear();
            }

           
        }

        #endregion

        #region Insert

        private void Insert(DiscountCountGoodsEO item, DiscountsData disDate, System.Guid uidAction)
        {
            T_DiscountCountGoods tDiscountCountGoods = new T_DiscountCountGoods();
            tDiscountCountGoods.Dcg_Guid = item.Dcg_Guid;
            tDiscountCountGoods.Dcg_CountValueMin = item.Dcg_CountValueMin;
            tDiscountCountGoods.Dcg_CountValueMax = item.Dcg_CountValueMax;
            tDiscountCountGoods.Dcg_PercentDiscount = item.Dcg_PercentDiscount;
            tDiscountCountGoods.Dcg_IsActive = item.Dcg_IsActive;

            disDate.InsertT_DiscountCountGoods(tDiscountCountGoods);


            T_LinkDCG tLinkDcg = new T_LinkDCG();
            tLinkDcg.Ldcg_Guid = System.Guid.NewGuid();
            tLinkDcg.Dcg_Guid = item.Dcg_Guid;
            tLinkDcg.A_Guid = uidAction;

            disDate.InsertT_LinkDCG(tLinkDcg);
        }

        #endregion

        #region Update

        private void Update(DiscountCountGoodsEO item, DiscountsData disDate)
        {
            T_DiscountCountGoods tDiscountCountGoods = disDate.SelectDiscountCountByUid(item.Dcg_Guid);

            //tDiscountCountGoods.Dcg_Guid = item.Dcg_Guid;
            tDiscountCountGoods.Dcg_CountValueMin = item.Dcg_CountValueMin;
            tDiscountCountGoods.Dcg_CountValueMax = item.Dcg_CountValueMax;
            tDiscountCountGoods.Dcg_PercentDiscount = item.Dcg_PercentDiscount;
            tDiscountCountGoods.Dcg_IsActive = item.Dcg_IsActive;
        }

        #endregion

        #region Delete
        
        private void Delete(Guid uidDcg, Guid uidAction, DiscountsData disDate)
        {
            disDate.DeleteT_DiscountCountGoods(uidDcg, uidAction);
        }

        #endregion

        #region Валидация

        public bool Validate(List<DiscountCountGoodsEO> lstDiscountCountGoodsEO)
        {
            if (lstDiscountCountGoodsEO.Count == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        #endregion

    }

    public class LinkDcgEO
    {
        private System.Guid Ldcg_Guid { get; set; }
        private System.Guid Dcg_Guid { get; set; }
        private System.Guid A_Guid { get; set; }
    }

    /// <summary>
    /// Класс скидок по времени действия
    /// </summary>
    public class DiscountTimeEO
    {
        #region Поля класса

        public Guid Dt_Guid { get; set; }
        public DateTime Dt_TimeBegin { get; set; }
        public DateTime Dt_TimeEnd { get; set; }
        public Double Dt_PercentDiscount { get; set; }
        public Boolean Dt_IsActive { get; set; }
        public List<LinkDtEO> lstLinkDtEO { get; set; }
        public Boolean bIsUpdate { get; set; }

        #endregion

        #region Конструктор

        public DiscountTimeEO()
        {
            Dt_Guid = Guid.Empty;
            Dt_TimeBegin = DateTime.Parse("01.01.1753"); //DateTime.MinValue;
            Dt_TimeEnd = DateTime.MaxValue;
            Dt_PercentDiscount = 0.0;
            Dt_IsActive = false;
            lstLinkDtEO = null;
            bIsUpdate = false;
        }

        public DiscountTimeEO(Guid Dt_Guid, DateTime Dt_TimeBegin, DateTime Dt_TimeEnd, double Dt_PercentDiscount, bool Dt_IsActive, List<LinkDtEO> lstLinkDtEO, bool bIsUpdate)
        {
            this.Dt_Guid = Dt_Guid;
            this.Dt_TimeBegin = Dt_TimeBegin;
            this.Dt_TimeEnd = Dt_TimeEnd;
            this.Dt_PercentDiscount = Dt_PercentDiscount;
            this.Dt_IsActive = Dt_IsActive;
            this.lstLinkDtEO = lstLinkDtEO;
            this.bIsUpdate = bIsUpdate;

        }

        #endregion

        #region Select
        
        /*
        /// <summary>
        /// Получить скидки (T_DiscountTime) по GUID акции 
        /// </summary>
        /// <param name="uid">GUID акции </param>
        /// <returns>IEnumerable</returns>
        public IEnumerable GetDiscountTimeByAction(System.Guid uid)
        {
            DiscountsData DisDate = new DiscountsData();
            return DisDate.SelectDiscountTimeByAction(uid);
        }
        */

        /// <summary>
        /// Получить скидки (T_DiscountTime) по GUID акции 
        /// </summary>
        /// <param name="uid">GUID акции</param>
        /// <returns>List  DiscountTimeEO </returns>
        public List<DiscountTimeEO> GetDiscountTimeByAction(Guid uid)
        {
            DiscountsData DisDate = new DiscountsData();

            List<DiscountTimeEO> lstDiscountTimeEO = new List<DiscountTimeEO>();

            foreach (T_DiscountTime item in DisDate.SelectDiscountTimeByAction(uid))
            {
                lstDiscountTimeEO.Add(new DiscountTimeEO(item.Dt_Guid, item.Dt_TimeBegin,item.Dt_TimeEnd, item.Dt_PercentDiscount, item.Dt_IsActive, null, false));
            }

            return lstDiscountTimeEO;
        }

        #endregion
        
        #region Общий save
        /// <summary>
        /// Общий save
        /// </summary>
        /// <param name="lstDiscountTimeEO">лист с сохраняемыми позициями</param>
        /// <param name="lstDiscountTimeEOforDel">лист с удаляемыми позициями</param>
        /// <param name="uidAction">Guid акции</param>
        /// <returns></returns>
        public bool Save(List<DiscountTimeEO> lstDiscountTimeEO, List<DiscountTimeEO> lstDiscountTimeEOforDel, Guid uidAction)
        {
            DiscountsData DisDate = new DiscountsData();
            try
            {
                // --- Insert и Update ---

                foreach (DiscountTimeEO item in lstDiscountTimeEO)
                {
                    // если Dt_Guid == Empty значит это новый клиент и надо сделать Insert
                    if (item.Dt_Guid == Guid.Empty)
                    {
                        item.Dt_Guid = Guid.NewGuid();
                        Insert(item, DisDate, uidAction);
                        DisDate.SaveChanges(); // сохраняем изминения в БД
                    }
                    else
                    {
                        // если Dt_Guid != Empty значит это существующий клиент
                        // если item.bIsUpdate=true значит   и надо сделать Update
                        if (item.Dt_Guid != Guid.Empty && item.bIsUpdate)
                        {
                            Update(item, DisDate);
                            DisDate.SaveChanges(); // сохраняем изминения в БД
                        }
                    }
                }

                // --- Delete ---

                foreach (DiscountTimeEO item in lstDiscountTimeEOforDel)
                {
                    if (item.Dt_Guid.CompareTo(System.Guid.Empty) == 0) { continue; }

                    Delete(item.Dt_Guid, uidAction, DisDate);
                    DisDate.SaveChanges(); // сохраняем изминения в БД
                }

                return true;
            }
            catch (Exception e)
            {
                var uu= e.Message;
                return false;
            }
            finally
            {
                lstDiscountTimeEO.Clear();
                lstDiscountTimeEOforDel.Clear();
                
            }
        }

        #endregion

        #region Insert

        private void Insert(DiscountTimeEO item, DiscountsData disDate, System.Guid uidAction)
        {
            T_DiscountTime tDiscountTime = new T_DiscountTime();
            tDiscountTime.Dt_Guid = item.Dt_Guid;
            tDiscountTime.Dt_TimeEnd = item.Dt_TimeEnd;
            tDiscountTime.Dt_TimeBegin = item.Dt_TimeBegin;
            tDiscountTime.Dt_PercentDiscount = item.Dt_PercentDiscount;
            tDiscountTime.Dt_IsActive = item.Dt_IsActive;

            disDate.InsertT_DiscountTime(tDiscountTime);


            T_LinkDT tLinkDt = new T_LinkDT();
            tLinkDt.Ldt_Guid = System.Guid.NewGuid();
            tLinkDt.Dt_Guid = item.Dt_Guid;
            tLinkDt.A_Guid = uidAction;

            disDate.InsertT_LinkDT(tLinkDt);
        }

        #endregion

        #region Update

        private void Update(DiscountTimeEO item, DiscountsData disDate)
        {
            T_DiscountTime tDiscountTime = disDate.SelectDiscountTimeByUid(item.Dt_Guid);

            //tDiscountCountGoods.Dcg_Guid = item.Dcg_Guid;
            tDiscountTime.Dt_TimeBegin = item.Dt_TimeBegin;
            tDiscountTime.Dt_TimeEnd = item.Dt_TimeEnd;
            tDiscountTime.Dt_PercentDiscount = item.Dt_PercentDiscount;
            tDiscountTime.Dt_IsActive = item.Dt_IsActive;
        }

        #endregion

        #region Delete

        private void Delete(Guid uidDt, Guid uidAction, DiscountsData disDate)
        {
            disDate.DeleteT_DiscountTime(uidDt, uidAction);
        }


        #endregion
        


    }

    public class LinkDtEO
    {
        private System.Guid Ldt_Guid { get; set; }
        private System.Guid Dt_Guid { get; set; }
        private System.Guid A_Guid { get; set; }
    }


}
